/**
 * 封装请求拦截器和响应拦截器
 * 每一个请求都会经过这里
 * @author 十一
 * @version v1.5.0
 */
import axios from "axios";
import {Message} from "element-ui";
import storage from "../storage/storageHelper.js";
import apiPath from "@/common/request/api";

const service = axios.create({
	baseURL: "https://localhost:44366/api/",  // 请求根路径
	// timeout: 3 * 1000  // 超时时间，单位：秒
});

/**
 * 添加请求拦截
 */
service.interceptors.request.use(
	config => {
		// 配置请求头，JSON格式发送
		config.headers = {
			"Content-Type": "application/json"
		};
		// 如果请求的不是登录接口
		if (config.url !== apiPath.adminLogin.url) {
			let tokenStr = storage.get("token");
			if (tokenStr === "键值不存在：token") {
				// Message.error("登录超时，请重新登录");
				setTimeout(() => {
					window.location.href = "/";  // 跳转登录页
				}, 3200);
				return config;
			} else {
				config.headers.Authorization = "Bearer " + tokenStr.token;  // 配置请求头，Token
			}
		}
		return config;
	},
);

/**
 * 添加响应拦截器
 */
service.interceptors.response.use(
	response => {
		let demo = response.config.url;
		if (demo === apiPath.adminLogin.url) {
			let tokenPara = {
				userID: response.data.data.userID,
				token: response.data.data.token,
			}
			storage.set("token", JSON.stringify(tokenPara), response.data.data.expires, true);
		}
		return response.data;
	},
	error => {
		if (error && error.response) {
			switch (error.response.status) {
				case 400:
					error.message = "错误请求";
					break;
				case 401:
					error.message = "登录超时，请重新登录";
					break;
				case 403:
					error.message = "拒绝访问";
					break;
				case 404:
					error.message = "请求错误，为找到该资源";
					break;
				case 408:
					error.message = "请求超时";
					break;
				case 500:
					error.message = "服务端错误";
					break;
				case 501:
					error.message = "网络未实现";
					break;
				case 502:
					error.message = "网络错误";
					break;
				case 503:
					error.message = "服务不可用";
					break;
				case 504:
					error.message = "网络超时";
					break;
				case 505:
					error.message = "http版本不支持该请求";
					break;
				default:
					error.message = `连接错误${error.response.status}`;
			}
		} else {
			// 超时处理
			if (JSON.stringify(error).includes("timeout")) {
				Message.error("服务器响应超时，请刷新当前页");
			}
			error.message = "连接服务器失败";
		}
		Message.error(error.message);
		if(error.message === "登录超时，请重新登录" && error.response.status == 401){
			setTimeout(() => {
				window.location.href = "/";  // 跳转登录页
			}, 3200);
		}
		return Promise.resolve(error.response);
	}
);

export default service;
